# coding=utf-8

import sys
import time
import datetime

from builtins import int

sys.path.append("..")
from common.mysql.connect import MysqlConnector
from common.redis.connect import RedisConnector
from common.utils.time import turn_ts_to_date
from common.utils.time import get_yesterday_date
from common.utils.time import turn_date_to_ts
from models.manager import get_dict_of_mid_and_bid
from logic.depart_logic import DepartmentLogic


def department_sale_info(mysql_db_order, department_id, date):
    """ 部门每天销售信息汇总
    """
    # 根据时间戳获取当天的开始和结束时间戳，作为基准
    ts_start = turn_date_to_ts(date)
    ts_end = ts_start + 60 * 60 * 24 - 1

    # 部门逻辑控制
    depart_logic = DepartmentLogic()

    # 获取写数据的数据库连接实例
    mysql_db_data = MysqlConnector('data')

    sql_insert = "insert into department (`department_id`, `date`, `order_num`, `order_amount`,\
         `refund_order_num`, `refund_order_amount`) values "

    goods_sale_res = depart_logic.get_department_everyday_sale_info(mysql_db_order, department_id, ts_start, ts_end)
    cur_date = turn_ts_to_date(ts_start) + '.000'
    if not goods_sale_res:
        # 当天没有售出，td中写入一条空值
        sql_insert += " (%d, %d, %d, %f, %d, %f) " % (department_id, ts_start, 0, 0.00, 0, 0.00)
    else:
        # 当天有售出，汇总售出结果，并写入td
        sale_num_amount = cal_sale_num_amount(goods_sale_res)
        sql_insert += " (%d, %d, %d, %f, %d, %f) " % \
        (department_id, ts_start, sale_num_amount['sale_num'], sale_num_amount['sale_amount'], 0, 0.00)

    exec_res = mysql_db_data.execute(sql_insert)
    if not exec_res:
        return False
    return True


if __name__ == '__main__':
    """ 部门相关数据处理
    """
    # 获取要处理的日期
    if len(sys.argv) == 2:
        # 外部传递进来
        date = sys.argv[1]
    else :
        # 默认取前一天的日期
        date = datetime.datetime.strftime(get_yesterday_date(), "%Y-%m-%d")

    redis_14 = RedisConnector(14)
    mysql_db_order = MysqlConnector('order')

    while True:
        time.sleep(0.1)
        departm_id_pop = redis_14.rpop('department_id_list')
        redis_14.lpush('department_id_list', departm_id_pop)

        if departm_id_pop and (not redis_14.sismember('departm_list_' + date, departm_id_pop)):
            res = department_sale_info(mysql_db_order, int(departm_id_pop), date)
            if res:
                redis_14.sadd('departm_list_' + date, departm_id_pop)
        else :
            print(date + " no more data")
            break
